package org.iks.store.business.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.iks.common.pojo.message.Attachment;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Author kzou
 * Date 2024/2/16
 * Description:
 */
@Slf4j
public class AttachmentTypeHandler implements TypeHandler<List<Attachment>> {
    @Override
    public void setParameter(PreparedStatement ps, int i, List<Attachment> parameter, JdbcType jdbcType) throws SQLException {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String value = objectMapper.writeValueAsString(parameter);
            ps.setString(i, value);
        } catch (JsonProcessingException e) {
            log.warn("json writeValueAsString error {} {}", parameter, e.getMessage());
            ps.setString(i, null);
        }
    }

    @Override
    public List<Attachment> getResult(ResultSet rs, String columnName) throws SQLException {
        String attachmentJson = rs.getString(columnName);
        return tryParseAttachment(attachmentJson);
    }

    @Override
    public List<Attachment> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String attachmentJson = rs.getString(columnIndex);
        return tryParseAttachment(attachmentJson);
    }

    @Override
    public List<Attachment> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String attachmentJson = cs.getString(columnIndex);
        return tryParseAttachment(attachmentJson);
    }

    public List<Attachment> tryParseAttachment(String attachmentArrayJson) {
        if (attachmentArrayJson == null || attachmentArrayJson.isEmpty()) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(attachmentArrayJson, new TypeReference<List<Attachment>>(){});
        } catch (JsonProcessingException e) {
            log.warn("parse to json error {},{}", attachmentArrayJson, e.getMessage());
            return null;
        }
    }
}
